#!/bin/bash

echo "tf卡挂载路径:$1"
echo "设备ip:$2"
echo "设备端口:$3"
echo "需要替换ip端口的文件:$4"
echo "设备生成的固件bin文件目录:$5"
echo "设备固件生成脚本文件目录:$6"
echo "生成的需要copy的固件文件名:$7"

if [ -z "$4" ]; then
    echo "设备执行文件不能为空"
    exit 1
fi

if [ -z "$5" ]; then
    echo "设备固件目录不能为空"
    exit 1
fi

content=$(cat "$4")
echo "content:$content"

if [ -z "$2" ]; then
    echo "ip不能串为空"
else
    echo "-----开始替换ip----"

    ip_address=$(echo "$content" | grep -oE '([0-9]*\.){3}[0-9]*')
    echo "ip_address:$ip_address"

    sed -i "s/${ip_address}/$2/g" "$4"
fi

if [ -z "$3" ]; then
    echo "-------端口不能为空-------"
else
    echo "-----$3开始替$4换端口$result----"

    result=$(echo "$content" | sed -n 's/.*-p \([0-9]\+\).*/\1/p')

    echo "port:$result"

    sed -i "s/-p [0-9]\+/-p $3/" "$4"

fi

# 执行设备执行文件
echo "-----开始执行设备执行文件-----"
IFS=',' read -r -a array <<< "$7"

bash "$6"

# 输出数组的元素
for elem in "${array[@]}"; do
echo "传递的数组元素是：$elem"
  bin_file=$(find "$5" -name "$elem" | head -n 1)
  if [ -n "$bin_file" ]; then
    echo "检测到生成的固件文件: $bin_file"

    target_dir="$1"
    if [ ! -d "$target_dir" ]; then
        echo "目标目录 $target_dir 不存在，创建中..."
        mkdir -p "$target_dir"
    fi

    mv "$bin_file" "$target_dir"
    echo "目标目录 $target_dir "
    echo "目标目录 $bin_file "
    echo "已将 $bin_file 移动到 $target_dir"
  else
    echo "未检测到需要生成的固件文件$bin_file文件"
  fi
done
